const d = {}

$.get('http://localhost:3000/comments', function (comments) {
    d.comments = comments

    $('.comments ul').html(template('tpl', { data: d }));
})
$('#submit').on('click', function (e) {
    const content = $('#comment').val()
    const name = $('#name').val()

    if (content == '' || name == '') {
        alert('昵称或内容不能为空')
        return
    }

    $.post('http://localhost:3000/comments', {
        author: name,
        content: content
    }, function (data) {
        console.log(data);

        //更新页面
        $.get('http://localhost:3000/comments', function (comments) {
            d.comments = comments;

            $('.comments ul').html(template('tpl', { data: d }));
        })
    })
});

$('.comments ul').on('click', 'a', function (e) {
    e.preventDefault();

    const id = $(this).prev().text().split('')[0];
    $.ajax({
        url: 'http://localhost:3000/comments/' + id,
        type: 'delete',
        success: function(r) {
            $.get('http://localhost:3000/comments', function (comments) {
                d.comments = comments;

                $('.comments ul').html(template('tpl', { data: d }));
            })
        }
    })
})